package com.wang.controller.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @Classname JWTUtil
 * @Description TODO
 * @Date 2024/10/9 15:05
 * @Created by pc
 */
public class JWTUtil {

    // 声明一个秘钥
    private static final String TOKEN = "token!Q@W3e4r";

    /**
     * 生成token
     *
     * @param map 传入的payload
     * @return 返回token
     */
    public static String getToken(Map<String, String> map){
        JWTCreator.Builder builder = JWT.create();
        // 设置声明 用户数据
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        // 设置过期时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,6000);
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(TOKEN));
    }

    /**
     * 验证token
     *
     * @param token
     */
    public static DecodedJWT verify(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN)).build();
        return jwtVerifier.verify(token);
    }

    /**
     * 获取token中payload
     *
     * @param token
     * @return
     */
    public static DecodedJWT getToken(String token) {
        return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }
}
